package org.lele.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.lele.dto.AssetsImportTemplateDto;
import org.lele.dto.ProjectPayExportDto;
import org.lele.handler.CascadeWriteHandler;
import org.lele.handler.ExcelSelectorDataWriteHandler;
import org.lele.handler.RowBackGroundWriteHandler;
import org.lele.handler.TitleHandler;
import org.lele.utils.ExcelUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.spring.web.plugins.Docket;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Author: fanYuLe
 * @CreateTime: 2024-11-04  13:39
 * @Description:
 */
@RestController
@RequestMapping("/excel")
@Api(tags = "excel导入导出")
public class ExcelController {

    @PostMapping("/exportTemplate")
    @ApiOperation("导出excel模板")
    public void exportTemplate(HttpServletResponse response) throws IOException {
        //第二三列级联下拉选择设置  资产类别和权属
        List<String> provNameList = new ArrayList<String>();
        provNameList.add("浙江省");
        provNameList.add("广东省");
        // 整理数据，放入一个Map中，mapkey存放父地点，value 存放该地点下的子区域
        Map<String, List<String>> siteMap = new HashMap<String, List<String>>();
        siteMap.put("浙江省", CollUtil.newArrayList("杭州市", "金华市", "宁波市"));
        siteMap.put("广东省", CollUtil.newArrayList("广州市", "深圳市", "韶光市"));

        //其他列下拉选择设置
        //资产性质 在第四列  代码对应的索引值为4
        HashMap<Integer, String[]> dropDownMap = new HashMap<>();
        String[] s = {"1","2","3"};
        dropDownMap.put(4,s);


        // 自定义策略  设置第一行数据为黄色  (short) 13对应黄色
        Set<Integer> yellowRowsSet = new HashSet<>();
        yellowRowsSet.add(1);//第一行
        RowBackGroundWriteHandler handler = new RowBackGroundWriteHandler(yellowRowsSet, (short) 13);

        Map<Integer, Short> requiredMap = ExcelUtils.getRequiredMap(AssetsImportTemplateDto.class);
        Map<Integer, String> notationMap = ExcelUtils.getNotationMap(AssetsImportTemplateDto.class);
        //Map<Integer, ExcelSelectorResolve> selectedMap = getSelectedMap(clazz);
        ExcelSelectorDataWriteHandler writeHandler = new ExcelSelectorDataWriteHandler(notationMap, requiredMap);


        //模板示例数据
        ArrayList<AssetsImportTemplateDto> assetsImportTemplateDtos = new ArrayList<>();
        assetsImportTemplateDtos.add(getTemplateExample());
        // 写出数据
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("资产批量导入模板", "UTF-8") + ".xlsx");
        EasyExcel.write(response.getOutputStream(), AssetsImportTemplateDto.class)
                .sheet("模板")
                .registerWriteHandler(handler)
                .registerWriteHandler(new CascadeWriteHandler(provNameList, siteMap))
                .registerWriteHandler(new TitleHandler(dropDownMap))
                .registerWriteHandler(writeHandler)
                .doWrite(assetsImportTemplateDtos);

}


    @PostMapping("/exportLocalTemplate")
    @ApiOperation("导出写好的本地excel模板")
    public void exportLocalTemplate(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = null;
        // 设置URLEncoder.encode 防止中文乱码
        fileName = URLEncoder.encode("集团公司工程项目财务支出汇总表", "UTF-8").replaceAll("\\+", "%20");
        // 设置响应头
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        // 模板文件保存在springboot项目的resources/static下
        //ClassPathResource resource = new ClassPathResource("/static/集团公司工程项目财务支出汇总表.xlsx");
        //ClassPathResource resource = new ClassPathResource("static/集团公司工程项目财务支出汇总表.xlsx");
        ClassPathResource resource = new ClassPathResource("static/3.xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(resource.getInputStream()).excelType(ExcelTypeEnum.XLSX).autoCloseStream(Boolean.FALSE).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        List<ProjectPayExportDto> exportData = new ArrayList<>();
        excelWriter.fill(exportData, fillConfig, writeSheet);
        Map<String, Object> map = new HashMap<>();
        map.put("total1", 1);
        map.put("total2", 2);
        map.put("total3", 3);
        map.put("total4", 4);
        map.put("total5", 5);
        excelWriter.fill(map, writeSheet);
        excelWriter.finish();
    }

    private AssetsImportTemplateDto getTemplateExample() {
        AssetsImportTemplateDto assetsImportTemplateDto = new AssetsImportTemplateDto();
        assetsImportTemplateDto.setAssetName("嘉兴市南湖区南江公寓3幢101室");
        assetsImportTemplateDto.setAssetCategory("住宅");
        assetsImportTemplateDto.setAssetSubCategory("自建商品房");
        assetsImportTemplateDto.setAssetProperty("住宅");
        assetsImportTemplateDto.setBuildingArea("121.3");
        assetsImportTemplateDto.setInsideSpaceArea("112");
        assetsImportTemplateDto.setAssetUsage("住宅用房");
        assetsImportTemplateDto.setLayout("2室1厅1卫");
        assetsImportTemplateDto.setFloor("第2层/共18层");
        assetsImportTemplateDto.setOrientation("朝南");
        assetsImportTemplateDto.setDecorationCondition("精装修");
        assetsImportTemplateDto.setLadderRoomRatio("一梯两户");
        assetsImportTemplateDto.setSuitBusiness("适合家庭居住");
        assetsImportTemplateDto.setAssetIntroduction("1、位置描述：房源位于城市的核心区域，交通便利，周边有完善的配套设施，如购物中心、医院、学校等。\n" +
                "2、面积与户型：该房源建筑面积为XX平方米，户型为X室X厅X卫，空间布局合理，采光和通风条件良好。\n" +
                "3、装修情况：房源采用精装修设计，配备了高品质的家具和家电，可以拎包入住。装修风格现代简约，营造出温馨舒适的居住氛围。\n" +
                "4、特色亮点：该房源具有独特的景观视野，可以俯瞰整个城市的美景。同时，小区内绿化率高，环境优美，是理想的居住场所。");
        assetsImportTemplateDto.setProvince("浙江省");
        assetsImportTemplateDto.setMunicipality("嘉兴市");
        assetsImportTemplateDto.setDistrict("南湖区");
        assetsImportTemplateDto.setStreet("解放街道");
        assetsImportTemplateDto.setAssetAddress("南江公寓3-101");
        assetsImportTemplateDto.setAssetDetailAddress("南江公寓3幢101室");
        assetsImportTemplateDto.setPropertyUnit("嘉兴海视嘉安智城科技有限公司");
        assetsImportTemplateDto.setPropertyArea("121.3");
        assetsImportTemplateDto.setSelfOwnedProperty("是");
        assetsImportTemplateDto.setPropertyCertificateNo("嘉房权证南字第123456号");
        assetsImportTemplateDto.setRentPerYear("120000");
        assetsImportTemplateDto.setLeaseDeposit("1200");
        assetsImportTemplateDto.setLeaseTermMonths("36");
        assetsImportTemplateDto.setPreemptiveRight("有");
        assetsImportTemplateDto.setRentPayRequire("采用先付款后使用的原则，租金每1年支付一次，具体以租赁合同约定为准。");
        assetsImportTemplateDto.setOtherTransactionConditions("1、履约保证金：首年成交价的前一个月租金。\n" +
                "2、出租标的使用过程中的水、电、物业管理费由承租方承担，具体以租赁合同约定为准。");
        assetsImportTemplateDto.setRentalPurpose("仅限于居住");
        assetsImportTemplateDto.setContactPersonPhone("0573-8123123");
        assetsImportTemplateDto.setContactPersonEmail("123@163.com");
        assetsImportTemplateDto.setIsEntrustOperate("是");
        assetsImportTemplateDto.setOperateCompanyInfos("嘉兴市南数运营科技有限公司");
        assetsImportTemplateDto.setRemark("第一行示例数据，需删除");
        return assetsImportTemplateDto;
    }
}
